import React, { useEffect, useRef, useState } from "react";
import { Route } from "react-router-dom";
import MyNavLink from "@/components/MyNavLink";
import { Button, Table } from "@douyinfe/semi-ui";
import { ColumnProps } from "@douyinfe/semi-ui/lib/es/table";

interface RecordType {
  completed: boolean;
  id: number;
  title: string;
  userId: number;
}

/* const initialData: RecordType[] = [
  { id: "1", name: "徐茂增", age: 28, gender: "男" },
  { id: "2", name: "阙芳芳", age: 27, gender: "女" }
]; */

// const url = "https://study.duyiedu.com/api/herolist"

/**
 * 休眠函数
 */
/* function sleep(times: number) {
  return new Promise(resovle => setTimeout(resovle, times));
} */

function About() {
  const [tableData, setTableData] = useState<RecordType[]>([]);
  const controler = useRef<AbortController>(); // 终止器

  const [count, setCount] = useState<number>(1);

  const columns: ColumnProps<RecordType>[] = [
    { title: "标题", dataIndex: "title" },
    { title: "用户id", dataIndex: "userId" },
    { title: "是否完成", dataIndex: "completed", render: text => (text ? "是" : "否") }
  ];

  const fetchData = async (index: number) => {
    controler.current = new AbortController();
    // await sleep(1000);
    const data: RecordType = await fetch(`https://jsonplaceholder.typicode.com/todos/${index}`, {
      signal: controler.current.signal
    }).then(res => res.json());
    setTableData([data]);
  };

  useEffect(() => {
    /* setTimeout(() => {
      fetchData().catch(() => {
        console.log("请求取消");
      });
    }, 3000); */

    // try...catch只能捕获同步错误，异步捕获不到
    /* try {
      fetchData();
    } catch (error) {
      console.log("abort");
    } */

    fetchData(count).catch(() => {
      console.log("取消请求");
    });

    return () => {
      controler.current?.abort();
    };
  }, [count]);

  return (
    <>
      <h3>About</h3>
      <Button onClick={() => setCount(count + 1)}>{count}</Button>
      <br />
      <br />
      <Table bordered columns={columns} dataSource={tableData} />
    </>
  );
}

function Home() {
  return <h3>Home</h3>;
}

const TestUseStateIfMounted: React.FC = props => {
  return (
    <>
      <h1>测试异步组件内存泄漏</h1>
      <MyNavLink to="/about">About</MyNavLink>
      &nbsp;&nbsp;
      <MyNavLink to="/home">Home</MyNavLink>
      <section>
        <Route path="/about" element={<About />} />
        <Route path="/home" element={<Home />} />
        {/* <Redirect to="/about" /> */}
      </section>
    </>
  );
};
export default TestUseStateIfMounted;
